<template>
  <div class="opts">
    <div class="opt-item">
      <label for="">观测间隔</label>
      <input type="number" v-model="state.stateInterval" />
    </div>
    <div class="opt-item">
      <label for="">最低高度</label>
      <input type="number" v-model="state.bottom" :min="0" />
    </div>
    <div class="opt-item">
      <label for="">最高高度</label>
      <input type="number" v-model="state.up" :min="state.bottom" />
    </div>
    <div class="opt-item">
      <label for="">时间范围</label>
      <el-time-picker v-model="state.times" is-range range-separator="To" start-placeholder="起始时间" end-placeholder="结束时间" />
    </div>
    <div class="opt-item">
      <label for="">时间分钟</label>
      <input type="number" v-model="state.timeInterval" />
    </div>
    <ColorMap />
  </div>
  <div class="btns">
    <button class="btn" @click="analyse">分析</button>
    <button class="btn" @click="clean">清除</button>
  </div>
</template>

<script setup>
  import { onBeforeUnmount, onMounted, watch, reactive } from 'vue';
  import useDraw, { DrawType } from '@/hooks/useDraw';
  import { ElNotification } from 'element-plus';
  import { ElTimePicker } from 'element-plus';
  import { SunshineAnalysis } from 'cgak';
  import ColorMap from '@/components/ColoMap.vue';

  const state = reactive({
    tiped: false,
    bottom: 50,
    up: 100,
    loading: false,
    stateInterval: 50,
    timeInterval: 30,
    times: [new Date(), new Date(new Date().getTime() + 6 * 60 * 60 * 1000)],
  });

  const analyser = new SunshineAnalysis(window.viewer, {
    startDate: state.times[0],
    endDate: state.times[1],
    stateBaseHeight: state.bottom,
    stateExtrudeHeight: state.up,
    stateInterval: state.stateInterval,
    timeInterval: state.timeInterval * 60,
  });
  const { drawStart, drawStop, drawClear } = useDraw(window.viewer, {
    type: DrawType.POLYGON,
    finishCallback: positions => {
      if (positions.length >= 3) {
        state.loading;
        analyser?.analyse(positions).finally(() => {
          state.loading = false;
        });
      }
    },
  });

  const analyse = () => {
    if (!state.tiped) {
      ElNotification({ message: '点击鼠标左键绘制视线，每两点分析一次，点击右键结束。', duration: 5000 });
      state.tiped = true;
    }
    drawStart();
  };

  const clean = () => {
    drawStop();
    drawClear();
    analyser?.clear();
  };

  watch(
    () => state,
    () => {
      analyser?.initOption({
        startDate: state.times[0],
        endDate: state.times[1],
        stateBaseHeight: Number(state.bottom),
        stateExtrudeHeight: Number(state.up),
        stateInterval: Number(state.stateInterval),
        timeInterval: Number(state.timeInterval) * 60,
      });
    },
    { deep: true }
  );

  onBeforeUnmount(() => {
    clean();
  });
</script>
